<template>
  <div class="dataInput">
    <div>
      <!-- 标题 -->
      <div class="title">
        <img src="@/assets/images/icon/dataInput/卡编辑.png" />
        <span> 信息填报</span>
      </div>
      <!-- 新增填报项 -->
      <el-input
        v-model="newKey"
        class="newKeyInputer"
        placeholder="请输入需要新增的属性名"
      ></el-input>
      <button @click="createInput">
        <img src="@/assets/images/icon/dataInput/数量-增加.png" />
        新增
      </button>
      <!-- 默认填报项 -->
      <div class="defaultPart" v-for="(data, index) in textList" :key="index">
        <div></div>
        <p>{{ data.key }}</p>
        <img
          src="@/assets/images/icon/dataInput/删除2.png"
          @click="textList.splice(index, 1)"
        />
        <el-input
          v-model="data.value"
          :rows="2"
          type="textarea"
          placeholder="请输入"
        />
      </div>
      <!-- 上传附件 -->
      <div class="title">
        <img src="@/assets/images/icon/dataInput/上传.png" />
        <span> 附件上传</span>
      </div>
      <!-- 已上传附件 -->
      <button @click="upload" class="uploadButton">
        <img
          src="@/assets/images/icon/dataInput/云上传.png"
          style="margin-right: 0%"
        />上传
      </button>
      <input
        type="file"
        accept="*"
        style="display: none"
        onblur='this.value=""'
      />
      <el-upload
        v-model:file-list="appendixNameList"
        class="appendixNameList"
        multiple
        :on-remove="handleRemove"
      >
      </el-upload>
    </div>
    <!-- 确认/取消 -->
    <div class="controller">
      <button id="cancel" @click="returnMain">
        <img src="@/assets/images/icon/dataInput/取消.png" />
        返回
      </button>
      <button id="submit" @click="submit">
        <img src="@/assets/images/icon/dataInput/确认.png" />
        提交
      </button>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import { onMounted, getCurrentInstance, ref } from "vue";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import pubsub from "pubsub-js";
import axios from "axios";
import * as turf from "@turf/turf";

import message from "@/components/Message/showMessage";
import urlList from "@/store/urlList.json";

export default {
  name: "信息填写模块",
  data() {
    return {
      id: "",
      subList: [],
      featureData: {},
      type: "",
      textList: [
        {
          key: "名称",
          value: "默认名称",
        },
      ],
      newKey: "",
      appendixNameList: [
        {
          name: "已成功上传的附件会显示在这",
        },
      ],
      appendixList: [],
    };
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const { proxy } = getCurrentInstance();
    const fileInput = ref(null);

    onMounted(() => {
      makeTimeStamp();
      getFeatureData();
      subscribeList();
      readFile();
    });

    // 制作时间戳
    function makeTimeStamp() {
      let date = new Date();
      let month =
        date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let min =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let sec =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      proxy.id = "timeStamp_" + (Number(month) + 1) + day + hour + min + sec;
      // console.log(proxy.id);
    }

    // 接收要素
    function getFeatureData() {
      // 要素类型
      proxy.type = route.query.type;
      // 点标绘
      switch (proxy.type) {
        case "point":
          // 读取坐标值
          proxy.featureData = {
            type: "point",
            geometry: [
              [
                Number(route.query.geometry.split(",")[0]),
                Number(route.query.geometry.split(",")[1]),
              ],
            ],
            centerPoint: [
              Number(route.query.geometry.split(",")[0]),
              Number(route.query.geometry.split(",")[1]),
            ],
          };
          // 地图重定位
          pubsub.publish("setView", [
            proxy.featureData.geometry[0][0],
            proxy.featureData.geometry[0][1] + 210,
          ]);
          break;
        case "polyline":
          break;
        case "polygon":
          let list = route.query.geometry.split(",");
          // 地图重定位
          pubsub.publish("setView", [
            calculatingCenter(list)[0],
            calculatingCenter(list)[1] + 210,
          ]);
          // 读取坐标值
          let pointList = [];
          let points = [];
          for (let i = 0; i < list.length; i++) {
            if (list[i + 1] != undefined && list[i] > 100000) {
              pointList.push([list[i], list[i + 1]]);
              points.push([Number(list[i]), Number(list[i + 1])]);
            }
          }
          // 计算多边形面积
          console.log(points);
          let area = calculatePolygonArea(points);
          proxy.textList.push({
            key: "面积(㎡)",
            value: area,
          });
          proxy.featureData = {
            type: "polygon",
            geometry: route.query.geometry,
            centerPoint: calculatingCenter(list),
          };
          break;
      }
    }

    function calculatePolygonArea(vertices) {
      const numVertices = vertices.length;

      if (numVertices < 3) {
        // 无法构成多边形，返回0
        return 0;
      }

      let area = 0;

      for (let i = 0; i < numVertices; i++) {
        const currentVertex = vertices[i];
        const nextVertex = vertices[(i + 1) % numVertices]; // 下一个顶点

        const x1 = currentVertex[0];
        const y1 = currentVertex[1];
        const x2 = nextVertex[0];
        const y2 = nextVertex[1];

        area += x1 * y2 - x2 * y1; // 通过叉乘计算每个三角形的面积
      }

      // 最终的面积可能为负数，取绝对值
      return Math.abs(area / 2).toFixed(2);
    }

    // 计算多边形中心
    function calculatingCenter(list) {
      let latSum = 0;
      let lngSum = 0;
      for (let i = 0; i < list.length; i++) {
        if (i % 2 === 0) {
          latSum += Number(list[i]);
        } else {
          lngSum += Number(list[i]);
        }
      }
      return [latSum / (list.length / 2), lngSum / (list.length / 2)];
    }

    function subscribeList() {}

    // 新建填报项
    function createInput() {
      // 属性名唯一检查
      let isOnly = true;
      proxy.textList.forEach((element) => {
        if (element.key === proxy.newKey) isOnly = false;
      });
      if (isOnly) {
        proxy.textList.push({
          key: proxy.newKey === "" ? "默认属性" : proxy.newKey,
          value: "",
        });
        proxy.newKey = "";
      } else {
        message("已有同名属性", "error");
      }
    }

    // 上传附件
    function upload() {
      document.querySelector("input[type='file']").click();
    }

    // 读取附件文件
    function readFile() {
      proxy.tableData = [];
      // 查找控制启动的DOM元素
      var inputFile = document.querySelector("input[type='file']");
      // 创建文件读取对象
      var fileReader = new FileReader();
      // 绑定事件
      fileReaderAddListener(fileReader);
      // 启动读取
      inputFile.onchange = (event) => {
        // 读取选中的第一个文件
        var file = inputFile.files[0];
        // 分离出文件名
        let fileName = file.name.split(".")[0];
        // 分离出文件类型
        let fileType = file.name.split(".")[1];
        // fileReader.readAsArrayBuffer(file, "utf-8");
        // 以dataURL的格式，按给定的路径来读取文件
        fileReader.readAsDataURL(file);
        // 读取完成
        fileReader.onload = (readRes) => {
          let fileStream = readRes.target.result;
          // 附件信息存入
          proxy.appendixList.push({
            name: fileName,
            type: fileType,
            data: fileStream,
          });
          // 附件名存入
          proxy.appendixNameList.push({
            name: fileName + "." + fileType,
          });
        };
        fileInput.value = null;
      };
    }

    // 文件读取对象状态处理
    function fileReaderAddListener(reader) {
      // 读取出错
      reader.addEventListener("error", readErr);
      // 读取中断
      reader.addEventListener("abort", readErr);
    }

    // 读取出错或中断
    function readErr(err) {
      message("文件读取失败，请重试", "error");
      console.log(err);
    }

    // 删除附件文件
    function handleRemove(event) {
      // 读取删除文件的文件名
      let itemName = event.name;
      // 附件名列表更新
      proxy.appendixNameList.forEach((e) => {
        if (e.name === itemName) {
          proxy.appendixNameList.splice(proxy.appendixNameList.indexOf(e), 1);
        }
      });
    }

    // 提交信息
    function submit() {
      insertBasicalData();
      insertAppendixData();
    }

    // 上传属性信息
    function insertBasicalData() {
      // 坐标信息、属性信息
      // 补充事件id
      proxy.featureData["id"] = proxy.id;
      // 文字信息整合
      proxy.featureData["textDataList"] = proxy.textList;
      proxy.featureData["name"] = proxy.textList[0].value;
      // console.log(proxy.textList);
      console.log(proxy.featureData);
      axios({
        method: "get",
        url: urlList.serverURL + "insertBasicalData",
        params: JSON.stringify(proxy.featureData),
      }).then((res) => {
        console.log(res.data.code === 1 ? "上传成功" : "上传失败");
        message(res.data.msg, res.data.code === 1 ? "" : "error");
      });
    }

    //  删除属性信息
    function deleteBasicalData() {
      axios({
        method: "get",
        url: urlList.serverURL + "deleteBasicalData",
        params: { id },
      }).then((res) => {
        console.log(res.data);
      });
    }

    // 上传附件信息
    function insertAppendixData() {
      let promiseArr = [];
      proxy.appendixList.forEach((element) => {
        // 补充id
        element["id"] = proxy.id;
        promiseArr.push(
          axios({
            method: "post",
            url: urlList.serverURL + "insertAppendixData",
            data: { data: element },
          })
        );
      });
      Promise.all(promiseArr).then((res) => {
        res.forEach((element) => {
          console.log(element.data.code === 1 ? "上传成功" : "上传失败");
          message(element.data.msg, element.data.code === 1 ? "" : "error");
          if (element.data.code != 1) {
            deleteBasicalData();
          }
        });
      });
    }

    // 返回主页
    function returnMain() {
      router.push({
        path: "/mapLayout",
      });
    }

    return {
      fileInput,
      createInput,
      upload,
      handleRemove,
      submit,
      returnMain,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/variables.less";

.dataInput {
  position: absolute;
  top: 5.5%;
  left: 0.25%;
  height: 94%;
  width: 49.25%;
  background-color: white;
  z-index: 99999;
  border-radius: 5px;
  overflow: auto;
  > div {
    margin-top: 0.5%;
    max-height: 95%;
    overflow-y: auto;
    > .title {
      color: @mainColor;
      font-size: 200%;
      font-family: "HGCH_CNKI";
      border-bottom: @mainColor 2px solid;
      padding: 0.5%;
      > img {
        width: 40px;
        float: left;
        position: relative;
        bottom: 0px;
      }
      > span {
        margin-left: 5px;
      }
    }
    > .newKeyInputer {
      width: 300px !important;
      margin-left: 1%;
      margin-top: 1%;
    }
    > .defaultPart {
      padding: 1%;
      padding-top: 0%;
      > div:first-child {
        width: 5px;
        height: 20px;
        border-radius: 5px;
        background-color: @mainColor;
        margin-right: 0.5%;
        float: left;
        position: relative;
        top: 2px;
      }
      > p {
        display: inline-block;
        font-size: 120%;
        margin-right: 1%;
        margin-bottom: 0.5%;
        color: #5b5c5f;
      }
      > img {
        width: 15px;
        position: relative;
        top: -2px;
        left: -9px;
      }
      > .el-input {
        display: inline;
        font-size: 120%;
      }
    }
    > .appendixNameList {
      margin-left: 0.5%;
      width: 500px;
    }
    > .pictureList {
      margin-left: 1%;
      margin-top: 0.7%;
    }
  }
  > .controller {
    width: 100%;
    border-top: 2px solid @mainColor;
    background-color: white;
    box-shadow: -1px 0 3px 0.5px @mainColor;
    position: absolute;
    z-index: 99999;
    bottom: 0%;
    text-align: right;
    overflow: auto;
  }
}
.dataInput > div:first-child::-webkit-scrollbar {
  width: 5px;
  border-radius: 50px;
  background: white;
}
.dataInput > div:first-child::-webkit-scrollbar-thumb {
  border-radius: 50px;
  background: @mainColor;
}
button {
  border: 2px solid @mainColor;
  background-color: white;
  outline: none;
  padding: 0.1%;
  padding-bottom: 0%;
  border-radius: 5px;
  color: @mainColor;
  font-weight: bold;
  font-size: 130%;
  margin: 0.5%;
  > img {
    width: 25px;
    margin-right: -6%;
    display: inline-block;
    margin-bottom: 5%;
  }
}
button:hover {
  box-shadow: 0px 0 2px 1px @mainColor;
}
.uploadButton {
  width: 15%;
  margin: 0.7% 1%;
  > img {
    margin-top: 5%;
  }
}
.addPic {
  width: 25%;
}
</style>